package br.com.felix.util.swing;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;

/**
 * CellEditor that displays a ComboBox when the editing value is Boolean.
 * */
public class CustomizedCellEditor extends AbstractCellEditor implements TableCellEditor{

	private static final long serialVersionUID = 1205523365881683667L;
	private JTextField txtField = new JTextField();
	private JComboBox cboBoolean = new JComboBox();
	private boolean editingComponentIsBoolean = false;
	
	public CustomizedCellEditor(){
		cboBoolean.addItem(new Boolean(true));
		cboBoolean.addItem(new Boolean(false));
		
		cboBoolean.addItemListener(new ItemListener(){
			public void itemStateChanged(ItemEvent e) {
				stopCellEditing();
			}
		});
		
		txtField.addKeyListener(new KeyAdapter(){
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					stopCellEditing();
				}
			}
		});
	}
	
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		if (value instanceof Boolean){
			Boolean bValue = (Boolean)value;
			cboBoolean.setSelectedItem(bValue);
			editingComponentIsBoolean = true;
			return cboBoolean;
		}
		editingComponentIsBoolean = false;
		if(value == null)txtField.setText("");
		else txtField.setText(value.toString());
		return txtField;
	}
	

	public Object getCellEditorValue() {
		if(editingComponentIsBoolean){
			return cboBoolean.getSelectedItem();
		}
		return txtField.getText();
	}

}
